// src/components/FilePreview/index.tsx
import { Modal, Tabs, Button } from "antd";
import { message } from "../../utils/customMessage";
import { useState, useEffect } from "react";
import * as pdfjsLib from "pdfjs-dist";
import * as XLSX from "xlsx";
import { http } from "../../utils/request";
import { UpOutlined, DownOutlined } from "@ant-design/icons";

// 动态加载 worker
if (typeof window !== "undefined" && "Worker" in window) {
  pdfjsLib.GlobalWorkerOptions.workerSrc = "/pdf.worker.min.js";
}

interface FileItem {
  id: number;
  fileName: string;
  filePath: string;
  fileUrl: string | null;
  updateTime: string;
}

interface FilePreviewProps {
  visible: boolean;
  file: FileItem | null;
  onClose: () => void;
  searchText?: string;
}

interface SheetData {
  name: string;
  data: any[][];
}

interface SearchResult {
  pageNum: number;
  element: HTMLElement;
  text: string;
}

const FilePreview: React.FC<FilePreviewProps> = ({
  visible,
  file,
  onClose,
  searchText,
}) => {
  const [sheetData, setSheetData] = useState<SheetData[]>([]);
  const [activeSheet, setActiveSheet] = useState<string>("");
  const [searchResults, setSearchResults] = useState<SearchResult[]>([]);
  const [currentSearchIndex, setCurrentSearchIndex] = useState(0);

  console.log(file, "file-------");

  useEffect(() => {
    if (visible && file) {
      handlePreview();
    }
  }, [visible, file, searchText]);

  // 重置搜索状态
  useEffect(() => {
    if (!visible || !searchText) {
      setSearchResults([]);
      setCurrentSearchIndex(0);
    }
  }, [visible, searchText]);

  const handlePreview = async () => {
    if (!file?.fileUrl) {
      message.error("文件地址不存在");
      onClose();
      return;
    }

    try {
      const fileType = file.fileName.split(".").pop()?.toLowerCase();

      switch (fileType) {
        case "xlsx":
        case "xls":
          await previewExcel(file.fileUrl);
          break;
        case "doc":
          await previewDocAsPdf(file.filePath);
          break;
        case "docx":
          await previewDocAsPdf(file.fileUrl);
          break;
        case "pdf":
          break;
        default:
          message.error("不支持的文件类型");
          onClose();
      }
    } catch (error) {
      console.error("预览错误:", error);
      message.error("预览失败");
      onClose();
    }
  };

  const previewDocAsPdf = async (filePath: string) => {
    try {
      const result = await http.get(
        `/api/uploadFile/getDocFile?filePath=${encodeURIComponent(filePath)}`
      );

      if (+result.status === 200) {
        const pdfUrl = result.data || result.data.url || result.data.pdfUrl;

        if (pdfUrl) {
          console.log("获取到的 PDF 地址:", pdfUrl);
          await previewPdf(pdfUrl);
        } else {
          message.error("未获取到有效的 PDF 地址");
        }
      } else {
        message.error(result.message || "获取文档失败");
      }
    } catch (error) {
      console.error("doc 文件预览失败:", error);
      message.error("doc 文件预览失败");
    }
  };

  const previewExcel = async (url: string) => {
    try {
      const response = await fetch(url);
      console.log(response, "response");
      const arrayBuffer = await response.arrayBuffer();
      const workbook = XLSX.read(arrayBuffer, { type: "array" });

      const sheets: SheetData[] = workbook.SheetNames.map((sheetName) => {
        const worksheet = workbook.Sheets[sheetName];
        const data = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
        return {
          name: sheetName,
          data: data,
        };
      });

      setSheetData(sheets);
      if (sheets.length > 0) {
        setActiveSheet(sheets[0].name);
      }
    } catch (error) {
      message.error("Excel 预览失败");
    }
  };

  const previewPdf = async (url: string) => {
    try {
      const response = await fetch(url);
      const arrayBuffer = await response.arrayBuffer();

      // 添加字体处理配置
      const pdf = await pdfjsLib.getDocument({
        data: arrayBuffer,
        // 启用字体回退机制
        standardFontDataUrl: `//cdn.jsdelivr.net/npm/pdfjs-dist@${pdfjsLib.version}/standard_fonts/`,
        // 禁用字体嵌入检查，使用系统字体
        disableFontFace: false,
        // 启用字体回退
        useSystemFonts: true,
        // 设置字体映射
        fontExtraProperties: true,
      }).promise;

      const previewContainer = document.getElementById("preview-container");
      if (previewContainer) {
        previewContainer.innerHTML = "";

        // 获取容器尺寸
        const containerWidth = previewContainer.clientWidth - 40; // 减去padding
        const containerHeight = previewContainer.clientHeight - 40;

        const foundResults: SearchResult[] = [];

        for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
          const page = await pdf.getPage(pageNum);
          const originalViewport = page.getViewport({ scale: 1.0 });

          // 计算自适应缩放比例
          const scaleX = containerWidth / originalViewport.width;
          const scaleY = containerHeight / originalViewport.height;
          const scale = Math.min(scaleX, scaleY, 1.5); // 限制最大缩放为1.5

          const viewport = page.getViewport({ scale });

          const pageContainer = document.createElement("div");
          pageContainer.style.position = "relative";
          pageContainer.style.marginBottom = "20px";
          pageContainer.style.textAlign = "center"; // 居中显示
          pageContainer.id = `page-${pageNum}`;

          const pageLabel = document.createElement("div");
          pageLabel.innerText = `第 ${pageNum} 页`;
          pageLabel.style.margin = "10px 0";
          pageLabel.style.fontWeight = "bold";
          pageContainer.appendChild(pageLabel);

          // 创建页面包装器，用于居中显示
          const pageWrapper = document.createElement("div");
          pageWrapper.style.display = "inline-block";
          pageWrapper.style.position = "relative";
          pageWrapper.style.maxWidth = "100%";
          pageWrapper.style.overflow = "hidden";
          pageWrapper.style.border = "1px solid #e8e8e8";
          pageWrapper.style.borderRadius = "4px";
          pageWrapper.style.backgroundColor = "#fff";
          pageWrapper.style.boxShadow = "0 2px 8px rgba(0,0,0,0.1)";

          const canvas = document.createElement("canvas");
          const context = canvas.getContext("2d");
          canvas.width = viewport.width;
          canvas.height = viewport.height;
          canvas.style.maxWidth = "100%";
          canvas.style.height = "auto";
          canvas.style.display = "block";

          if (context) {
            // 设置渲染选项，处理字体问题
            const renderContext = {
              canvasContext: context,
              viewport: viewport,
              // 启用字体回退
              enableWebGL: false,
              // 设置字体渲染选项
              textLayerMode: 2, // 强制渲染文本层
              renderInteractiveForms: false,
            };

            await page.render(renderContext).promise;

            pageWrapper.appendChild(canvas);
            pageContainer.appendChild(pageWrapper);

            if (searchText && searchText.trim()) {
              try {
                const textContent = await page.getTextContent({
                  // 启用字体回退
                  normalizeWhitespace: true,
                  disableCombineTextItems: false,
                });

                const pageText = textContent.items
                  .map((item) => ("str" in item ? item.str : ""))
                  .join(" ")
                  .toLowerCase();

                if (pageText.includes(searchText.toLowerCase())) {
                  // 计算该页面的匹配次数
                  const searchLower = searchText.toLowerCase();
                  let matchCount = 0;
                  let index = pageText.indexOf(searchLower);

                  while (index !== -1) {
                    matchCount++;
                    index = pageText.indexOf(searchLower, index + 1);
                  }

                  // 为整个页面添加高亮背景
                  const textLayerDiv = document.createElement("div");
                  textLayerDiv.style.position = "absolute";
                  textLayerDiv.style.left = "0";
                  textLayerDiv.style.top = "0";
                  textLayerDiv.style.width = "100%";
                  textLayerDiv.style.height = "100%";
                  textLayerDiv.style.pointerEvents = "none";
                  textLayerDiv.style.backgroundColor = "rgba(255, 255, 0, 0.3)";
                  textLayerDiv.style.border = "2px solid orange";
                  pageWrapper.appendChild(textLayerDiv);

                  // 创建搜索结果标记
                  const searchIndicator = document.createElement("div");
                  searchIndicator.style.position = "absolute";
                  searchIndicator.style.top = "5px";
                  searchIndicator.style.right = "5px";
                  searchIndicator.style.backgroundColor = "orange";
                  searchIndicator.style.color = "white";
                  searchIndicator.style.padding = "5px 10px";
                  searchIndicator.style.borderRadius = "3px";
                  searchIndicator.style.fontSize = "12px";
                  searchIndicator.style.fontWeight = "bold";
                  searchIndicator.style.zIndex = "1000";
                  searchIndicator.textContent = `找到 ${matchCount} 处匹配`;
                  searchIndicator.className = "search-result-indicator";

                  pageWrapper.appendChild(searchIndicator);

                  // 保存搜索结果
                  foundResults.push({
                    pageNum,
                    element: pageContainer,
                    text: searchText,
                  });
                }
              } catch (textError) {
                console.error("获取PDF文本内容失败:", textError);
              }
            }

            previewContainer.appendChild(pageContainer);
          }
        }

        // 保存搜索结果并导航到第一个
        setSearchResults(foundResults);
        if (foundResults.length > 0) {
          setCurrentSearchIndex(0);
          setTimeout(() => {
            foundResults[0].element.scrollIntoView({
              behavior: "smooth",
              block: "start",
              inline: "nearest",
            });
          }, 200);
          message.success(`找到 ${foundResults.length} 页包含搜索结果`);
        } else if (searchText && searchText.trim()) {
          message.info(`未找到关键字："${searchText}"`);
        }
      }
    } catch (error) {
      console.error("PDF 预览失败:", error);
      message.error("PDF 预览失败");
    }
  };

  // 导航到上一个搜索结果
  const goToPreviousResult = () => {
    if (searchResults.length === 0) return;

    const newIndex =
      currentSearchIndex > 0
        ? currentSearchIndex - 1
        : searchResults.length - 1;
    setCurrentSearchIndex(newIndex);

    searchResults[newIndex].element.scrollIntoView({
      behavior: "smooth",
      block: "start",
      inline: "nearest",
    });
  };

  // 导航到下一个搜索结果
  const goToNextResult = () => {
    if (searchResults.length === 0) return;

    const newIndex =
      currentSearchIndex < searchResults.length - 1
        ? currentSearchIndex + 1
        : 0;
    setCurrentSearchIndex(newIndex);

    searchResults[newIndex].element.scrollIntoView({
      behavior: "smooth",
      block: "start",
      inline: "nearest",
    });
  };

  const renderExcel = () => {
    if (!sheetData.length) return null;

    return (
      <div style={{ height: "100%", display: "flex", flexDirection: "column" }}>
        <Tabs
          activeKey={activeSheet}
          onChange={setActiveSheet}
          items={sheetData.map((sheet) => ({
            key: sheet.name,
            label: sheet.name,
            children: (
              <div style={{ overflow: "auto", flex: 1 }}>
                <table
                  style={{
                    borderCollapse: "collapse",
                    width: "100%",
                    backgroundColor: "#fff",
                    boxShadow: "0 1px 3px rgba(0,0,0,0.1)",
                  }}
                >
                  <tbody>
                    {sheet.data.map((row, rowIndex) => (
                      <tr key={rowIndex}>
                        {row.map((cell, cellIndex) => (
                          <td
                            key={cellIndex}
                            style={{
                              border: "1px solid #e8e8e8",
                              padding: "8px 12px",
                              textAlign: "left",
                              fontSize: "14px",
                              lineHeight: "1.5",
                              backgroundColor:
                                rowIndex === 0 ? "#fafafa" : "transparent",
                              fontWeight: rowIndex === 0 ? "bold" : "normal",
                              color: rowIndex === 0 ? "#262626" : "#595959",
                            }}
                          >
                            {cell}
                          </td>
                        ))}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ),
          }))}
        />
      </div>
    );
  };

  return (
    <Modal
      title={
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            paddingRight: "40px", // 给关闭按钮留出空间
          }}
        >
          <span style={{ fontSize: "16px", fontWeight: "500" }}>
            {file?.fileName}
          </span>
          {searchResults.length > 0 && (
            <div
              style={{
                display: "flex",
                alignItems: "center",
                gap: "8px",
                backgroundColor: "#f0f0f0",
                padding: "4px 12px",
                borderRadius: "6px",
                border: "1px solid #d9d9d9",
              }}
            >
              <span
                style={{
                  fontSize: "12px",
                  color: "#666",
                  minWidth: "60px",
                  textAlign: "center",
                }}
              >
                {currentSearchIndex + 1} / {searchResults.length}
              </span>
              <div style={{ display: "flex", gap: "4px" }}>
                <Button
                  size="small"
                  type="text"
                  icon={<UpOutlined />}
                  onClick={goToPreviousResult}
                  disabled={searchResults.length === 0}
                  style={{
                    width: "28px",
                    height: "28px",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    border: "1px solid #d9d9d9",
                    borderRadius: "4px",
                  }}
                  title="上一个搜索结果"
                />
                <Button
                  size="small"
                  type="text"
                  icon={<DownOutlined />}
                  onClick={goToNextResult}
                  disabled={searchResults.length === 0}
                  style={{
                    width: "28px",
                    height: "28px",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    border: "1px solid #d9d9d9",
                    borderRadius: "4px",
                  }}
                  title="下一个搜索结果"
                />
              </div>
            </div>
          )}
        </div>
      }
      open={visible}
      onCancel={onClose}
      width="64%"
      footer={null}
      destroyOnClose
      styles={{
        header: {
          paddingBottom: "16px",
          borderBottom: "1px solid #f0f0f0",
        },
      }}
    >
      <div
        id="preview-container"
        style={{
          height: "70vh",
          overflow: "auto",
          padding: "20px",
          backgroundColor: "#fff",
        }}
      >
        {/* 只在 pdf 时用 iframe，其他类型不变 */}
        {file?.fileName?.toLowerCase().endsWith(".pdf") ? (
          <iframe
            src={file.fileUrl || ""}
            width="100%"
            height="100%"
            style={{ border: "none", minHeight: "60vh" }}
            title="PDF预览"
          />
        ) : (
          sheetData.length > 0 && renderExcel()
        )}
      </div>
    </Modal>
  );
};

export default FilePreview;
